<template>
  <div>
    <Dialog :title="title" :visible="visible" class="single-column" :button-text="textBtn" :loading="loading" @close="handleClose" @confirm="submitForm">
      <div v-if="flag">
        <div class="divs">
          <p><span>小明</span><span>135*****0101</span></p>
          <p>此顾客还未预约</p>
          <p class="butl">
            <el-button class="submitButton" @click="returnBtn">返回</el-button>
            <el-button class="submitButtons" @click="addSubscribeBtn">增加预约</el-button>
          </p>
        </div>
      </div>
      <div v-else>
        <el-form v-show="!shows" ref="subscribeRef" :model="addSubscribeForm" :rules="subscribeRules" label-width="100px">
          <el-form-item label="顾客：" prop="customerName">
            <el-autocomplete v-model="addSubscribeForm.customerName" :fetch-suggestions="querySearch" placeholder="姓名、手机号、编号" clearable @select="handleSelect" />
            <span style="color:#aaaaaa;font-size: 12px;">{{ notif }}</span>
          </el-form-item>
          <!-- <el-form-item label="预约类型：" prop="appointmentType">
            <dictionary-selector code="swan_cutomer_yylx" :value.sync="addSubscribeForm.appointmentType" @change="handleSelector" />
          </el-form-item> -->
          <el-form-item label="预约时间：" prop="appointmentDate">
            <el-col>
              <el-form-item prop="appointmentDate">
                <el-date-picker v-model="addSubscribeForm.appointmentDate" :picker-options="pickerOptions" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期" @change="handleDate" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="appointmentTime" class="dateStyle">
                <el-select v-model="addSubscribeForm.appointmentTime" class="el-select-y" placeholder="请选择时段" clearable>
                  <el-option v-for="item in cities" :key="item.value" :label="item.value" :value="item.value" :disabled="item.label === '不可预约' ? true : false">
                    <span style="float: left">{{ item.value }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item class="el-select-y" label="咨询分类：" prop="advisoryClassification">
            <!-- <el-cascader v-model="addSubscribeForm.advisoryClassification" style="width: 100%" :options="consultingOptions" :props="optionsProps" @change="handleConsultType" /> -->
            <el-select v-model="addSubscribeForm.advisoryClassification" placeholder="请选择咨询分类">
              <el-option v-for="item in consultingOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item v-if="addSubscribeForm.appointmentType === '治疗/复查'" label="项目" prop="projectName">
            <el-select v-model="addSubscribeForm.projectName" placeholder="请选择项目" value-key="id">
              <el-option v-for="item in projectNameOptions" :key="item.id" :label="item.projectName" :value="item.projectName" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="咨询师：" prop="receiverName">
            <el-select v-model="addSubscribeForm.receiverName" filterable class="el-select-y">
              <el-option v-for="item in receiverOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约说明：" prop="appointmentRemark">
            <el-input v-model="addSubscribeForm.appointmentRemark" type="textarea" resize="none" :autosize="{ minRows: 3 }" />
          </el-form-item>
        </el-form>
        <el-form v-show="shows" ref="lookSubscribeRef" :rules="lookSubscribeRules" :model="lookSubscribeForm" label-width="100px">
          <el-form-item label="顾客：">{{ lookSubscribeForm.customerName }}</el-form-item>
          <el-form-item label="预约类型：">{{ lookSubscribeForm.appointmentType }}</el-form-item>
          <el-form-item label="咨询师：">{{ lookSubscribeForm.receiverName }}</el-form-item>
          <el-form-item label="预约时间：">{{ lookSubscribeForm.appointmentDate }}
            {{ lookSubscribeForm.appointmentTime }}</el-form-item>
          <el-form-item v-if="searchForm.appointmentStatus !== '已取消'" label="项目分类：">{{ lookSubscribeForm.advisoryClassification }}</el-form-item>
          <el-form-item v-if="title !== '取消预约'" label="预约说明：">{{ lookSubscribeForm.appointmentRemark || "无" }}</el-form-item>
          <el-form-item v-if="title !== '预约签到' && title !== '取消预约'" label="预约状态：">
            {{ lookSubscribeForm.appointmentStatus }}{{ lookSubscribeForm.arrivalTime ? lookSubscribeForm.arrivalTime : "" }}
          </el-form-item>
          <el-form-item v-if="searchForm.appointmentStatus === '已取消'" class="el-select-y" label="取消原因：">{{ lookSubscribeForm.cancelReason }}</el-form-item>
          <el-form-item v-if="searchForm.appointmentStatus === '已取消'" class="el-select-y" label="取消备注：">{{ lookSubscribeForm.cancelRemark }}</el-form-item>
          <el-form-item v-if="title === '取消预约'" label="取消原因：" :prop="title === '取消预约' ? 'cancelReason' : ''">
            <dictionary-selector class="el-select-y" code="RESERVE_CANCAL_CODE" :value.sync="lookSubscribeForm.cancelReason" placeholder="请选择取消原因" />
          </el-form-item>
          <el-form-item v-if="title === '取消预约'" class="textarea-border" label="取消备注：" prop="cancelRemark">
            <el-input v-model="lookSubscribeForm.cancelRemark" type="textarea" :autosize="{ minRows: 3 }" />
          </el-form-item>
        </el-form>
      </div>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
export default {
  components: {
    Dialog,
  },
  props: {
    title: {
      type: String,
      default: '',
    },
    textBtn: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    flag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const times = Date.now() - 24 * 60 * 60 * 1000;
          return time.getTime() < times;
        },
      },
      notif: "",
      searchForm: {},
      addSubscribeForm: {
        appointmentType: "咨询预约",
      },
      urls: '',
      massages: '',
      optionsProps: {
        children: "children",
        label: "name",
        value: "name",
        checkStrictly: true, // 选择任意一项
      },
      chargeData: {},
      selectCustomerData: {}, // 新增选中顾客
      seleteDate: "", // 预约选择日期
      cities: [], // 预约时段
      projectNameOptions: [],
      lookSubscribeForm: {},
      restaurants: [], // 顾客数据
      consultingOptions: [],
      receiverOptions: [],
      shows: false,
      loading: false,
      subscribeRules: {
        customerName: [
          { required: true, message: "请输入顾客名称", trigger: "change" },
        ],
        // appointmentType: [
        //   { required: true, message: "请选择预约类型", trigger: "change" },
        // ],
        projectName: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        appointmentDate: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
      },
      lookSubscribeRules: {
        cancelReason: [
          { required: true, message: "请选择取消原因", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    addSubscribeBtn(row, data) {
      this.$nextTick(() => {
        if (this.title === '修改预约') {
          this.urls = 'reception/subscribe/eaditAdvisory';
          this.massages = '修改预约';
        } else {
          this.urls = 'reception/subscribe/addappointment';
          this.massages = '新增预约';
        }
        if (row && row.id) {
          this.addSubscribeForm = row;
        }
        if (this.title === '重新预约') {
          this.massages = '重新预约';
          this.addSubscribeForm.appointmentDate = '';
          this.addSubscribeForm.appointmentTime = '';
          this.$nextTick(() => {
            this.$refs.subscribeRef.clearValidate();
          });
        }
        this.searchForm = data;
        this.shows = false;
        this.loadAll();
        this.handleSelector();
      });
    },
    lookBtn(row, data) {
      this.shows = true;
      this.lookSubscribeForm = row;
      this.searchForm = data;
    },
    signInBtn(row, data) {
      this.shows = true;
      this.lookSubscribeForm = row;
      this.searchForm = data;
      if (row.appointmentType === "治疗/复查") {
        this.lookSubscribeForm.advisoryClassification = row.projectName;
      } else {
        this.lookSubscribeForm.advisoryClassification = row.advisoryClassification;
      }
    },
    cancelBtn(row, data) {
      this.shows = true;
      this.lookSubscribeForm = row;
      this.searchForm = data;
    },
    async loadAll() {
      // 所有顾客详情
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
      // 咨询分类
      const consultingData = await this.$api[
        "reception/subscribe/consulttype"
      ]();
      if (consultingData.code === 200) {
        this.consultingOptions = consultingData.data.result;
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        if (restaurant.value) {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        } else {
          return null;
        }
      };
    },
    handleSelect(item) {
      this.selectCustomerData = item;
      this.notif = "";
      this.getProjectName(item);
    },
    // 根据职位名称获取所有人员
    async handleSelector(val) {
      // 1 咨询师 2 主治医生
      if (val === "治疗/复查") {
        val = "主治医生";
      } else {
        val = "咨询师";
      }
      const receiverData = await this.$api[
        "reception/subscribe/getAllByJobName"
      ]({ hospitalJobName: val });
      if (receiverData.code === 200) {
        this.receiverOptions = receiverData.data;
      }
    },
    // 顾客已购项目
    async getProjectName(item) {
      if (item.id) {
        const res = await this.$api['reception/triage/getCustomerMessageById']({ id: item.id });
        if (res.code !== 200) return this.$message.error(res.msg);
        this.projectNameOptions = res.data;
      }
      // console.log(this.projectNameOptions, "this.seleteCustomerInDatathis.seleteCustomerInData");
      // if (this.projectNameOptions.appointmentType === '手术预约') {
      //   this.notif = "该顾客今日有手术预约,已智能填入";
      // }
      // const res = await this.$api["reception/subscribe/customerIdAllByOrderList"]({ customerId: this.selectCustomerData.id });
      // if (res.code === 200) {
      //   this.projectNameOptions = res.data;
      // }
    },
    // 监听选中预约日期变化
    async handleDate() {
      function p(s) {
        return s < 10 ? "0" + s : s;
      }
      const myDate = new Date();
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1;
      const day = myDate.getDate();
      const hours = myDate.getHours();
      const minutes = myDate.getMinutes();
      const dates = year + "-" + p(month) + "-" + p(day) + "-" + p(hours) + "-" + p(minutes);
      const currentDate = dates.split("-").join("");
      if (this.addSubscribeForm.appointmentDate) {
        // 预约时段列表
        const timeData = await this.$api["reception/subscribe/getCreateList"]({
          dictionaryId: "785558903319429120",
        });
        if (timeData.code !== 200) return this.$message.error(timeData.message);
        timeData.data.map((item) => {
          item.value = item.name + "~" + item.content;
          const aTime = this.addSubscribeForm.appointmentDate + "-" + item.content;
          const bTime = aTime.split(":").join("");
          this.seleteDate = bTime.split("-").join("");
          if (Number(currentDate) > Number(this.seleteDate)) {
            item.label = "不可预约";
          } else {
            item.label = "可预约";
          }
        });
        this.cities = timeData.data;
      }
    },
    async getUpdateReportData() {
      const res = await this.$api["reception/subscribe/updateReport"]({ ...this.lookSubscribeForm });
      if (res.code !== 200) return this.$message.error(res.msg);
      if (this.title === "预约签到" || this.title === "添加分诊") {
        this.$message.success('预约签到成功！');
      } else {
        this.$message.success("取消预约成功！");
      }
      this.$emit("update:visible", false);
      this.$emit("success");
    },
    // 提交-确认
    submitForm() {
      if (this.title === "新增预约" || this.title === "修改预约" || this.title === "重新预约") {
        this.$refs.subscribeRef.validate(async(valid) => {
          if (valid) {
            this.loading = true;
            if (this.addSubscribeForm.appointmentTime && this.addSubscribeForm.appointmentDate) {
              // if (this.addSubscribeForm.appointmentType === "咨询预约") {
              //   this.addSubscribeForm.advisoryClassification = this.addSubscribeForm.advisoryClassification[0];
              // }
              if (this.selectCustomerData && this.selectCustomerData.sex) {
                this.selectCustomerData.customerSex = this.selectCustomerData.sex;
                this.selectCustomerData.customerName = this.selectCustomerData.name;
                this.selectCustomerData.customerId = this.selectCustomerData.id;
                this.selectCustomerData.customerPhone = this.selectCustomerData.phone;
              }
              // console.log(this.addConsultingForm, "9999");
              const res = await this.$api[this.urls]({ ...this.addSubscribeForm, ...this.selectCustomerData });
              if (res.code !== 200) { return this.$message.error(this.massages + '失败'); }
              this.$message.success(this.massages + '成功！');
              this.$emit("update:visible", false);
              this.$refs.subscribeRef.resetFields();
              this.$emit("success");
              this.loading = false;
            } else {
              this.$message.info("必须选择预约时间！");
            }
          }
        });
      } else if (this.title === "预约签到") {
        this.getUpdateReportData();
        this.$emit("addTriage", this.lookSubscribeForm);
      } else if (this.title === "取消预约") {
        this.$refs.lookSubscribeRef.validate((valid) => {
          if (valid) {
            if (!this.lookSubscribeForm.cancelReason) {
              this.$message.error("请选择取消原因");
            }
            this.getUpdateReportData();
            this.$refs.lookSubscribeRef.resetFields();
          }
        });
      } else {
        this.$emit("update:visible", false);
      }
    },
    // 关闭
    handleClose() {
      if (this.$refs.subscribeRef) {
        this.$refs.subscribeRef.resetFields();
      }
      if (this.$refs.lookSubscribeRef) {
        this.$refs.lookSubscribeRef.resetFields();
      }
      this.$emit("update:visible", false);
      // this.$refs['subscribeRef'].resetFields();
    },
    // 返回
    returnBtn() {
      this.searchForm = {};
      this.$emit("update:visible", false);
      this.$emit("update:flag", false);
      this.$emit("success");
    },
    handleConsultType(val) {
      console.log(val);
      if (val.length > 0 && val instanceof Array) {
        this.$set(this.addSubscribeForm, 'advisoryClassification', val[0]);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
// .el-form {
  // width: 50%;
  // float: left;
  // margin: 20px 148px;
// }
.dateStyle {
  margin-bottom: 0 !important;
}
.el-cascader__dropdown,/deep/.el-autocomplete-suggestion{
  border: 1px solid #D3DFF7;
}
/deep/.el-textarea__inner{
  border: 1px solid #9baed3;
}
/deep/.el-cascader__dropdown{
  border: 1px solid #9baed3;
}
/deep/.el-input__prefix, /deep/.el-input__suffix{
  color: #9baed3;
}
// /deep/.el-autocomplete-suggestion{
//   border: 1px solid #000;
// }
// /deep/.el-popper.el-cascader__dropdown{
//   border: 1px solid #000;
// }

/deep/.el-textarea__inner{
    border: 1px solid #D3DFF7 !important;
}

.submitButton,.submitButtons{
  width: 186px !important;
  height: 30px !important;
  background: #0278DC;
  border-radius: 4px;
  border: none;
  color:#fff;
}
.submitButton,.submitButtons{
  width: 186px !important;
  height: 30px !important;
  background: #0278DC !important;
  border-radius: 4px !important;
  color:#fff !important;
}
.submitButton:hover{
  background: #4791d1 !important;
}
.submitButtons{
  background: #EFF3FB !important;
  color: #0278DC !important;
}
.submitButtons:hover{
  background: #46a6ff !important;
  color: #fff !important;
}
.butl{
  display: flex;
  justify-content: center;
  .submitButton{
    margin-right: 45px;
  }
  .submitButtons{
    margin-left: 45px;
  }
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
